import router from '@/router/index'
import store from '@/store/index'
import nProgress from 'nprogress'
// import { asyncRoutes } from '@/router/index'
import 'nprogress/nprogress.css' // 引入进度条样式
const topath = ['/login', '/404']// 白名单
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  const token = store.getters.token
  // 有token的时候
  if (token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      const userbefo = store.state.user.userInfo
      if (Object.keys(userbefo).length <= 0) {
        const { roles } = await store.dispatch('user/getUser')
        const otherRoutes = await store.dispatch('permission/filterRoutes', roles.menus)
        router.addRoutes([
          ...otherRoutes,
          { path: '*', redirect: '/404', hidden: true }
        ])
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
        return
      }
      next()
    }
  } else {
    // 没有token的时候
    if (topath.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach((to, from) => {
  nProgress.done()
})
